// pages/personal/sales/addSalesOrder/addSalesOrder.js
import { create, query } from '../../../../utils/service.js'
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:'',
    clientId: '', 
    clientName: '',
    clientFactory: '',
  
    cargo_info:[],
    dockingInfo:{},
    weighMateriel:[],
    remark:'',//留言
    time:'',
    date: '',
    startTime: '',
    startX: 0, //开始坐标
    startY: 0,
    items:[],
    sortList:[],
    className:'',
    total:0,
    materielList:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this 
    console.log(options)
    const id = options.id
    query({
      url:"api/waste/sell/read",
      params:{id},
      back:function(data){
        const item = data.result
        app.globalData.Weighed_Goods_Information = item
        console.log(item)
        const cargo_info = item.cargo_info
        that.setData({
          item:item,
          cargo_info:cargo_info
        })
      }
    })




    for (var i = 0; i < 2; i++) {
      this.data.items.push({
        content: i + " 向左滑动删除哦,向左滑动删除哦,向左滑动删除哦,向左滑动删除哦,向左滑动删除哦",
        isTouchMove: false //默认全隐藏删除
      })
    }
    this.setData({
      items: this.data.items,
      id:id
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const that = this
    const clientId = app.globalData.clientId
    console.log(clientId)
    const clientName = app.globalData.clientName//客户名称 
    const clientFactory = app.globalData.clientFactory //客户公司名称
  
    const dockingInfo = app.globalData.dockingInfo
   
    const showname =  app.globalData.showname
    const customerInfo =  app.globalData.customerInfo
    const sortList = app.globalData.sortList
    const prices = []
    const materielList = app.globalData.materielList
    console.log(materielList)
    const firstName =  app.globalData.firstListName
    //开支信息
    const salesPayInfoLists = app.globalData.salesPayInfoLists
    let  payTotal = 0
    
    salesPayInfoLists.length > 0 && salesPayInfoLists.map(payItem => {
      const money = payItem.price * 1
      payTotal = (payTotal * 1 + money * 1).toFixed(2)
    })
    //填写的货品信息
    const newGoodsInfo = app.globalData.newGoodsInfo
    console.log(newGoodsInfo)
    let cargo_info = that.data.cargo_info
    if (newGoodsInfo.id){
      for(let i=0;i<cargo_info.length;i++){
        if (cargo_info[i].id == newGoodsInfo.id) {
          cargo_info[i] = newGoodsInfo
        }
      }
    }
    //辅材信息
    const weighMateriel = app.globalData.weighMateriel
    let metroTotal =0
    weighMateriel.length > 0 && weighMateriel.map(payItem => {
      const money = payItem.unit_price * payItem.pick_amount
      metroTotal = (metroTotal * 1 + money * 1).toFixed(2)
    })
    



    let showNameList = []
    for(let i=0;i<sortList.length;i++){
      sortList[i].sortWeight
      const price = sortList[i].pricevalue * sortList[i].sortWeight
      
      prices.push(price)
    }
    let total = 0
    for(let i=0;i<prices.length;i++){
      total += Number(prices[i])
      
    }
    
    //获取当前时间，格式YYYY-MM-DD
    var date = new Date();
    var seperator1 = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
    }
    var startTime = year + seperator1 + month + seperator1 + strDate;


    that.setData({
      clientId: clientId,
      clientName: clientName,
      customerInfo:customerInfo,
      clientFactory: clientFactory,
  

      dockingInfo: dockingInfo,

      startTime: startTime,
      sortList: sortList,
      total:total,
      salesPayInfoLists: salesPayInfoLists,//开支信息
      payTotal: payTotal,//开支合计
      newGoodsInfo:newGoodsInfo,
      cargo_info: cargo_info,
      weighMateriel: weighMateriel,//辅材信息
      metroTotal: metroTotal,//辅材合计
    })


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
  }, 
  bindTimeChange: function (e) {
    this.setData({
      time: e.detail.value
    })
  },
  //手指触摸动作开始 记录起点X坐标
  touchstartMetro: function (e) {
    //开始触摸时 重置所有删除
    this.data.weighMateriel.forEach(function (v, i) {
      if (v.isTouchMove)//只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      weighMateriel: this.data.weighMateriel
    })
  },
  //滑动事件处理
  touchmoveMetro: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index,//当前索引
      startX = that.data.startX,//开始X坐标
      startY = that.data.startY,//开始Y坐标
      touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
      //获取滑动角度
      angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
    that.data.weighMateriel.forEach(function (v, i) {
      v.isTouchMove = false

      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
      
    })
    //更新数据
    that.setData({
      weighMateriel: that.data.weighMateriel
    })
  },
  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },
  //删除事件
  delMetro: function (e) {
    console.log(e)
    this.data.weighMateriel.splice(e.currentTarget.dataset.index, 1)
    // let total = this.data.total
    // console.log(this.data.sortList)
    let weighMateriel = this.data.weighMateriel
    let prices = []
    for (let i = 0; i < weighMateriel.length; i++) {
      const price = weighMateriel[i].pick_amount * weighMateriel[i].unit_price
      prices.push(price)
    }
    let total = 0
    for (let i = 0; i < prices.length; i++) {
      total += Number(prices[i])
    }
    app.globalData.weighMateriel = weighMateriel
    this.setData({
      weighMateriel: this.data.weighMateriel,
      metroTotal: total
    })
  },
  //手指触摸动作开始 记录起点X坐标 --------删除货品
  touchstartPay: function (e) {
    //开始触摸时 重置所有删除
    this.data.salesPayInfoLists.forEach(function (v, i) {
      if (v.isTouchMove)//只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      salesPayInfoLists: this.data.salesPayInfoLists
    })
  },
  //滑动事件处理
  touchmovePay: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index,//当前索引
      startX = that.data.startX,//开始X坐标
      startY = that.data.startY,//开始Y坐标
      touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
      //获取滑动角度
      angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
    that.data.salesPayInfoLists.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })
    //更新数据
    that.setData({
      salesPayInfoLists: that.data.salesPayInfoLists
    })
  },
  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },
  //删除事件  
  delPay: function (e) {
    this.data.salesPayInfoLists.splice(e.currentTarget.dataset.index, 1)


    let salesPayInfoLists = this.data.salesPayInfoLists
    let payTotal = this.data.payTotal
    let money = [], newNumber = 0
    for (let i = 0; i < salesPayInfoLists.length; i++) {
      money.push(Number(salesPayInfoLists[i].price))
    }
    for (let j = 0; j < money.length; j++) {
      newNumber += money[j]
    }
    payTotal = newNumber.toFixed(2)
    console.log(payTotal)

    this.setData({
      salesPayInfoLists: this.data.salesPayInfoLists,
      payTotal: payTotal
    })
    app.globalData.salesPayInfoLists = this.data.salesPayInfoLists
  },
  onAddfucai:function(){
    wx.navigateTo({
      url: './extractMaterial/extractMaterial',
    })
  },
  onAdd: function () {
    wx.navigateTo({
      url: './enterProductInfo/enterProductInfo',
    })
  },
  onAddexp:function(){
    wx.navigateTo({
      url: './addPay/addPay',
    })
  },
  onchange:function(e){
    console.log(e)
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: './enterProductInfo/enterProductInfo?id='+id,
    })
  },
  onCar:function(e){
    const that = this 
    console.log(e)
    const car_number = e.detail.value
    that.setData({
      car_number: car_number
    })
  },
  onCarWeight: function (e) {
    const that = this
    console.log(e)
    const car_weight = e.detail.value
    that.setData({
      car_weight: car_weight
    })
   },  
  addBox: function (e) {
    const that = this
    const key = e.currentTarget.dataset.key
    const materielList = that.data.materielList
    materielList && materielList.map(item => {
      if (item.key == key) {
        if (!item.num) {
          item.num = 1
        } else {
          item.num++
        }
      }
    })
    app.globalData.materielList = materielList

    that.setData({
      materielList: materielList
    })
  },
  cutBox: function (e) {
    const that = this
    const key = e.currentTarget.dataset.key
    const materielList = that.data.materielList
    materielList && materielList.map(item => {
      if (item.key == key) {
        item.num--
      }
    })
    app.globalData.materielList = materielList

    that.setData({
      materielList: materielList
    })
  },
  onBlur:function(e){
    const that = this 
    const remark = e.detail.value
    that.setData({
      remark: remark
    })
  },
  //提交
  onSubmit:function(e){
    const that = this 
    const { id, car_number, car_weight, cargo_info, weighMateriel, salesPayInfoLists, remark } = that.data
    let  no_netwight 
    for(let i=0;i<cargo_info.length;i++){
      if (cargo_info[i].net_weight == '' || cargo_info[i].net_weight == null){
        no_netwight = false
      }
    }
    console.log(no_netwight)
    const data = {
      id:id,
      car_number: car_number,
      car_weight: car_weight,
      remark: remark,
      cargo_info: cargo_info,
      materiel_info: weighMateriel,
      other_price_info: salesPayInfoLists,
      is_draft:0
    }
    console.log(data)
    if ( !car_number || !car_weight){
      wx.showToast({
        title: '请填写车辆信息',
        icon:"none",
        deration:1000
      })
    } else if (no_netwight == false ){
      wx.showToast({
        title: '请填写货品信息',
        icon: "none",
        deration: 1000
      })
    }else{
      wx.showModal({
        title:'提示',
        content:"是否确认提交",
        success:function(res){
          if(res.confirm){
            create({
              url:"api/waste/sell/weigh",
              params:{...data},
              back:function(data){
                if(data.code == 200){
                  console.log(111)
                  wx.navigateTo({
                    url: './success/success?id='+that.options.id,
                  })
                }
              }
            })
          }
        }
      })
      console.log(1)
    }
  } 
})